from config.configs import ALPHA_DB_PORT, ALPHA_DB_HOST, DATA_PATH
import pymongo
from tools.funciton import read_json_file
import json
import requests
import os
import time
import hashlib
from urllib.parse import quote_plus


alpha = pymongo.MongoClient(ALPHA_DB_HOST, ALPHA_DB_PORT).alpha
jiwu = pymongo.MongoClient(ALPHA_DB_HOST, ALPHA_DB_PORT).jiwu
local = pymongo.MongoClient('127.0.0.1', 27017).test
file = os.path.join(DATA_PATH, 'add_spu_datas.json')


def alpha_insert_spu_sku():
    """新增货号尺码-alpha"""
    spuId = read_json_file(file)['data']['contents'][0]['spuId']
    spu_datas = read_json_file(file)['data']['contents'][0]['commodityInfo']
    spu_param = {'spuId': spuId, 'title': spu_datas['title'], 'categoryName': spu_datas['categoryName'],
                 'brandName': spu_datas['brandName'], 'brandId': spu_datas['brandId'],
                 'categoryId': spu_datas['categoryId'],
                 'articleNumber': spu_datas['articleNumber'], 'spuLogo': spu_datas['logoUrl'],
                 'createdAt': int(round(time.time() * 1000)), 'updatedAt': int(round(time.time() * 1000))}
    alpha.spus.insert_one(spu_param)
    sku_list = read_json_file(file)['data']['contents'][0]['commodityInfo']['skuInfoList']
    for i in range(len(sku_list)):
        items = sku_list[i]['skuPropsList']
        sorted_items = sorted(items, key=lambda x: x['level'])
        new_dict = {item['name']: item['value'] for item in sorted_items}
        json_string = json.dumps(new_dict, ensure_ascii=False)
        sku_param = {"spuId": spuId, "skuId": sku_list[i]['skuId'], "properties": json_string.replace(" ", ""),
                     'barcode': sku_list[i]['barCodeList'][0],
                     'status': 1,
                     "__v": 0, "createdAt": int(round(time.time() * 1000)), "updatedAt": int(round(time.time() * 1000))}
        alpha.skus.insert_one(sku_param)


def jiwu_insert_spu_sku():
    """新增货号尺码-集物（通过闪电仓申请预约单获取数据）"""
    spuId = read_json_file(file)['data']['appointSkuResponseList'][0]['spuId']
    spu_datas = read_json_file(file)['data']['appointSkuResponseList'][0]
    sku_datas = read_json_file(file)['data']['appointSkuResponseList']
    spu_param = {'spuId': spuId, 'title': spu_datas['title'],
                 'brandId': spu_datas['brandId'],
                 'categoryId': spu_datas['categoryId'],
                 'articleNumber': spu_datas['articleNumber'], 'spuLogo': spu_datas['logo'],
                 'createdAt': int(round(time.time() * 1000)), 'updatedAt': int(round(time.time() * 1000))}
    jiwu.spus.insert_one(spu_param)
    for i in range(len(sku_datas)):
        items = json.loads(sku_datas[i]['props'])
        sorted_items = sorted(items, key=lambda x: x['level'])
        print(sorted_items)
        new_dict = {item['name']: item['value'] for item in sorted_items}
        json_string = json.dumps(new_dict, ensure_ascii=False)
        sku_param = {"spuId": spuId, "skuId": sku_datas[i]['skuId'], "properties": json_string.replace(" ",""),
                     'barcode': sku_datas[i]['barCode'],
                     'status': 1,
                     "__v": 0, "createdAt": int(round(time.time() * 1000)), "updatedAt": int(round(time.time() * 1000))}
        jiwu.skus.insert_one(sku_param)


def alpha_insert_spu_sku_api():
    """新增货号尺码-（直接通过得物api查询数据）"""
    for i in range(len(read_json_file(file)['data'])):
        spuId = read_json_file(file)['data'][i]['spu_id']
        spu_datas = read_json_file(file)['data'][i]
        sku_datas = read_json_file(file)['data'][i]['skus']
        spu_param = {'spuId': spuId, 'title': spu_datas['title'],
                     'brandId': spu_datas['brand_id'], 'brandName': spu_datas['brand_name'],
                     'categoryId': spu_datas['category_id'],'categoryName': spu_datas['category_name'],
                     'articleNumber': spu_datas['article_number'], 'spuLogo': spu_datas['spu_logo'],
                     'createdAt': int(round(time.time() * 1000)), 'updatedAt': int(round(time.time() * 1000)), "status": 1}
        alpha.spus.insert_one(spu_param)
        for z in range(len(sku_datas)):
            items = json.loads(sku_datas[z]['properties'])
            sku_param = {"spuId": spuId, "skuId": sku_datas[z]['sku_id'], "properties": json.dumps(items, ensure_ascii=False).replace(" ",""),
                         'barcode': sku_datas[z]['barcode'],
                         'status': 1,
                         "__v": 0, "createdAt": int(round(time.time() * 1000)), "updatedAt": int(round(time.time() * 1000))}
            alpha.skus.insert_one(sku_param)


def local_insert_spu_sku_api():
    """新增货号尺码-（直接通过得物api查询数据）"""
    for i in range(len(read_json_file(file)['data'])):
        spuId = read_json_file(file)['data'][i]['spu_id']
        spu_datas = read_json_file(file)['data'][i]
        sku_datas = read_json_file(file)['data'][i]['skus']
        spu_param = {'spuId': spuId, 'title': spu_datas['title'],
                     'brandId': spu_datas['brand_id'], 'brandName': spu_datas['brand_name'],
                     'categoryId': spu_datas['category_id'],'categoryName': spu_datas['category_name'],
                     'articleNumber': spu_datas['article_number'], 'spuLogo': spu_datas['spu_logo'],
                     'createdAt': int(round(time.time() * 1000)), 'updatedAt': int(round(time.time() * 1000)), "status": 1}
        local.spus.insert_one(spu_param)
        for z in range(len(sku_datas)):
            items = json.loads(sku_datas[z]['properties'])
            sku_param = {"spuId": spuId, "skuId": sku_datas[z]['sku_id'], "properties": json.dumps(items, ensure_ascii=False).replace(" ",""),
                         'barcode': sku_datas[z]['barcode'],
                         'status': 1,
                         "__v": 0, "createdAt": int(round(time.time() * 1000)), "updatedAt": int(round(time.time() * 1000))}
            local.skus.insert_one(sku_param)


if __name__ == '__main__':
    alpha_insert_spu_sku_api()